package com.lagou.edu.mvcframework.proxy;

import com.lagou.edu.mvcframework.annotations.LagouController;
import com.lagou.edu.mvcframework.annotations.LagouService;
import com.lagou.edu.mvcframework.annotations.Security;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

public class SecurityProxy implements InvocationHandler {

    private Object target;

    public SecurityProxy(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (doSecurity(method, args)) {
            return method.invoke(target, args);
        } else {
            System.out.println("Security forbidden!");
            return "username is not in whitelist, forbidden!";
        }
    }

    private boolean doSecurity(Method method, Object[] args) {
        String methodName = method.getName();
        Class<?> clazz = target.getClass();
        Method[] methods = clazz.getDeclaredMethods();
        Method targetMethod = null;
        for (Method amethod : methods) {
            if (amethod.getName().equals(methodName)) {
                targetMethod = amethod;
                break;
            }
        }
        //check method's security annotation
        if (targetMethod.isAnnotationPresent(Security.class)) {
            Parameter[] praments = method.getParameters();
            String userName = "";
            int i = 0;
            for (Parameter param : praments) {
                if ("name".equals(param.getName())){
                    userName = (String)args[i];
                    break;
                }
                ++i;
            }
            Security annotation = targetMethod.getAnnotation(Security.class);
            String[] userNames = annotation.value();
            for(String name : userNames) {
                if (name.equals(userName)) {
                    return true;
                }
            }
            System.out.println(userName + " is not in whitelist, forbidden!");
            return false;
        } else {
            return true;
        }
    }
}
